<?php
	class UserHandler
	{
		// Membervariables
		private $_con = null;
		private $_userView = null;
		
		public function __construct(\DBConnection $dbconnection, \UserView $userView)
		{
			$this->_con = $dbconnection;
			$this->_userView = $userView;
		}
		
		// Returns the specified user if he exists.
		public function GetUser($username)
		{
			$classname = "User";
			$sql = "SELECT * FROM users WHERE username = ?";
			
			$stmt = $this->_con->Prepare($sql);
			
			$stmt->bind_param("s", $username);
			
			$arr = $this->_con->RunAndFetchObjects($stmt, $classname, "username");

			if (count($arr) == 1)
			{
				return $arr[$username];
			}
			else
			{
				return null;
			}	
		}
		
		// Returns a list of all the users in the database.
		public function GetUserList()
		{
			$classname = "User";
			$sql = "SELECT * FROM users";
			
			$stmt = $this->_con->Prepare($sql);
			
			$arr = $this->_con->RunAndFetchObjects($stmt, $classname, "id");
			
			return $arr;
		}
		
		// Adds a new user to the database.
		public function CreateNewUser(\User $user)
		{
			
			$sql = "INSERT INTO `users`(`id`, `username`, `password`, `salt`, `usertype`, `givenname`, `surname`, `email`)" .
			"VALUES (?,?,?,?,?,?,?,?)";
			
			$stmt = $this->_con->Prepare($sql);
			
			$stmt->bind_param("isssisss", $user->id, $user->username, $user->password, $user->salt, $user->usertype, $user->givenname, $user->surname, $user->email);
			
			$stmt->execute();
			
			$stmt->close();
			
			if ($this->GetUser($user->username) != null)
			{
				$this->_userView->UserAddedMessage($user);
			}
			else 
			{
				$this->_userView->UserFailedToAddMessage();
			}
		}
		
		// Removes a user from the database.
		public function RemoveUserFromDB($id, $username)
		{
			$sql = "DELETE FROM `users` WHERE id=?";
			
			$stmt = $this->_con->Prepare($sql);
			
			$stmt->bind_param("i", $id);
			
			$stmt->execute();
			
			$stmt->close();
			
			if ($this->GetUser($username) != null)
			{
				$this->_userView->FailedToRemoveUserMessage($username);
			}
			else 
			{
				$this->_userView->UserRemovedMessage($username);
			}
		}	
		
		// Encrypts the parameter and returns the encrypted string.
		public function Encrypt($stringToEncrypt)
		{
			$stringToEncrypt = MCRYPT_ENCRYPT(MCRYPT_RIJNDAEL_256, EncryptionConfig::GetKey(), $stringToEncrypt, MCRYPT_MODE_ECB, EncryptionConfig::GetIV());
			
			$stringToEncrypt = urlencode($stringToEncrypt);
			
			return $stringToEncrypt;
		}
		
		// Generates a salt to be added to a password.
		public function GenerateSalt($max)
		{
			$baseStr = time(). rand(0, 1000000) . rand(0, 1000000);
			$md5Hash = md5($baseStr);
			if ($max < 32)
			{
				$md5Hash = substr($md5Hash, 0, $max);	
			}
		
			return $md5Hash;	
		}
		
		// Returns the salt of the specefied User
		public function GetUserSalt(\User $user)
		{
			return $user->salt;	
		}		
	}		